package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TOrderDetailMapper;
import com.bwie.pojo.TOrderDetail;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbUser;
import com.bwie.service.IProdService;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.DataValueVo;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ProdEnum;
import com.bwie.vo.TbProdVo;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author Lenovo
* @description 针对表【tb_order】的数据库操作Service实现
* @createDate 2025-03-21 18:13:10
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    IUserService iUserService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    TOrderDetailMapper tOrderDetailMapper;
    @Autowired
    IProdService iProdService;

    @Override
    public R getOrderById(int orderId) {
        TbOrder tbOrder = tbOrderMapper.selectById(orderId);
        if(tbOrder == null){
            return R.ERROR(404,"订单不存在");
        }
        //获取用户信息：通过远程调用获取用户信息
//        String url = "http://localhost:9011/user/index/getUserById/" + tbOrder.getUserId();
//        R r = restTemplate.postForObject(url, null, R.class);
        R r = iUserService.getUserById(tbOrder.getUserId());
        if(r.getCode() != 200){
            return r;
        }
        //需要把R类里面的data转换为字符串，然后再把字符串转换为对象
        String data = JSON.toJSONString(r.getData());
        TbUser tbUser = JSON.parseObject(data, TbUser.class);
        tbOrder.setUser(tbUser);

        //获取订单明细
        LambdaQueryWrapper<TOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TOrderDetail::getOrderId,tbOrder.getOrderId());
        List<TOrderDetail> orderDetailList = tOrderDetailMapper.selectList(wrapper);
        tbOrder.setDetailList(orderDetailList);

        return R.OK(tbOrder);
    }

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        //构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        //获取分页数据
        Page<TbOrder> list = tbOrderMapper.getOrderList(page);
        return R.OK(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProdVo> prodVoList) {

        //获取消费者id
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(500,"请先登录");
        }
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);

        //判断商品是否有效
        BigDecimal totalAmount = new BigDecimal(0.0);
        Integer totalNum = 0;
        for (TbProdVo tbProdVo : prodVoList) {
            if(tbProdVo.getProdStatus() != ProdEnum.ONLINE.getCode()){
                return R.ERROR(500,"包含无效商品");
            }
            BigDecimal multiply = tbProdVo.getProdPrice().multiply(new BigDecimal(tbProdVo.getBuyNum()));
            totalAmount = totalAmount.add(multiply);
            totalNum += tbProdVo.getBuyNum();
        }

        //判断库存/较少库存
        //定义一个接口，统一扣减库存
        R r = iProdService.sucProdStock(prodVoList);
        if(r.getCode() != 200){
            return R.ERROR(500,"库存不足");
        }

        for (TbProdVo tbProdVo : prodVoList) {
            if(tbProdVo.getBuyNum() > tbProdVo.getProdStock()){
                return R.ERROR(500,"库存不足");
            }
            //TODD: 扣减库存
            //扣减库存：需使用openFeign

        }

        //生成订单
        TbOrder order = new TbOrder();
        order.setUserId(userId);
        String code = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        code += RandomUtil.randomNumbers(4);

        order.setOrderCode(code);
        order.setCreateTime(new Date());
        order.setOrderStatus(0);
        order.setOrderAmount(totalAmount);
        order.setProdCount(totalNum);

        tbOrderMapper.insert(order);

        //生成订单明细
        for (TbProdVo tbProdVo : prodVoList) {
            TOrderDetail detail = new TOrderDetail();
            detail.setOrderId(order.getOrderId());
            detail.setProdId(tbProdVo.getProdId());
            detail.setProdPrice(tbProdVo.getProdPrice());
            detail.setProdNum(tbProdVo.getBuyNum());

            tOrderDetailMapper.insert(detail);
        }

        return R.OK();
    }

    @Override
    public R getOrderAmountFormWeek() {
        //获取订单金额
        List<DataValueVo> amountFormWeek = tbOrderMapper.getOrderAmountFormWeek();

        //组装echarts数据
        ArrayList<String> xData = new ArrayList<>();
        ArrayList<Double> yData = new ArrayList<>();

        for (DataValueVo dataValueVo : amountFormWeek) {
            xData.add(dataValueVo.getName());
            yData.add(dataValueVo.getValue());
        }

        //返回数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("xData",xData);
        map.put("yData",yData);
        map.put("pieData",amountFormWeek);

        return R.OK(map);
    }
}




